from DrissionPage import SessionPage
from model.goods import *
from web.res import Res

@dataclass
class Page(Res):
    current_page:int = 0
    total:int = 0
    pageSize:int = 50


class GoodsSource:
    basePath = "http://gjx.0591cf.cn:30002/tugegjx"
    
    @classmethod
    def create(cls):
        return cls("16089762","88888888")
    
    def __init__(self,username,password):
        self.page = SessionPage()
        
        self.page.post(f'{self.basePath}/user/login',data={
            "userName": username,
            "loginPswd": password,
        })
        
    def getGoodsList(self,currentPage: int) -> Page:
        dataList = []
        self.page.get(f'{self.basePath}/sware/querySwarePage',params={
            "currentpage": currentPage
        })
        total = self.page("共有数据").text
        total = int(total[total.find("：")+1:total.find("条")])
        # pageSize = math.ceil(total / 50)
        trs = self.page.eles("x://tbody//tr")
        for tr in trs:
            goods = Goods.parse(tr)
            dataList.append(goods)
        return Page(data=dataList, current_page=currentPage, total=total, pageSize=50)

    def getDescImg(self,id: str) -> Res:
        self.page.get(f'{self.basePath}/sware/gotoInspectDescImg',params={
            "id": id,
        })
        tds = self.page.s_eles('tag:img')

        info = SKUInfo(id)
        for img in tds:
            info.imgList.append(img.attr("src"))
        return Res(data=info)

    def getSKUImg(self,id: str) -> Res:
        self.page.get(f'{self.basePath}/sware/gotoInspectSkuImg',params={
            "id": id,
        })
        tds = self.page.s_eles('@@tag()=td@@width')
        dataList: List[SKUInfo] = []
        for td in tds[2:]:
            title = td.text.replace("\n","").split("\t")[0]
            dataList.append(SKUInfo(id,title,[td("tag:img").attr("src")]))
        return Res(data=dataList)